package com.JL;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class JLRSACoder {
    public static final String KEY_ALGORITHM = "RSA";

    public static final String KEY_PROVIDER = "BC";

    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";

    static{
        try{
            Security.addProvider(new BouncyCastleProvider());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 初始化密钥对
     */

    public static Map<String, Object> initKeys(String seed) throws Exception {


        Map<String, Object> keyMap = new HashMap<String, Object>();

        Security.addProvider(new BouncyCastleProvider());

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM, KEY_PROVIDER);


        keyPairGenerator.initialize(1024, new SecureRandom(seed.getBytes()));

        KeyPair pair = keyPairGenerator.generateKeyPair();

        RSAPublicKey rsaPublicKey = (RSAPublicKey) pair.getPublic();

        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) pair.getPrivate();


        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(rsaPublicKey.getModulus().toString()), new BigInteger(rsaPublicKey.getPublicExponent().toString()));

        RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(rsaPrivateKey.getModulus().toString()), new BigInteger(rsaPrivateKey.getPrivateExponent().toString()));



        String pubKeystr= Base64.getEncoder().encodeToString((pubKeySpec.getModulus() + "----" + pubKeySpec.getPublicExponent()).getBytes());
        String priKeystr= Base64.getEncoder().encodeToString((priKeySpec.getModulus() + "----" + priKeySpec.getPrivateExponent()).getBytes());

        System.out.println("公钥：" + pubKeystr);

        System.out.println("私钥：" + priKeystr);

        keyMap.put("publicKey", pubKeystr);

        keyMap.put("privateKey", priKeystr);


        return keyMap;

    }



    /**
     * 私钥加密
     */

    public static byte[] encryptRSA(byte[] data, PrivateKey privateKey) throws Exception {

        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM, KEY_PROVIDER);

        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        int dataSize = cipher.getOutputSize(data.length);

        int blockSize = cipher.getBlockSize();

        int blockNum = 0;

        if (data.length % blockSize == 0) {
            blockNum = data.length / blockSize;
        } else {
            blockNum = data.length / blockSize + 1;
        }
        byte[] raw = new byte[dataSize * blockNum];
        int i = 0;
        while (data.length - i * blockSize > 0) {
            if (data.length - i * blockSize > blockSize) {
                cipher.doFinal(data, i * blockSize, blockSize, raw, i * dataSize);
            } else {
                cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * dataSize);
            }

            i++;

        }
        return raw;
    }


    /**
     * 公钥加密
     */

    public static byte[] decryptRSA(byte[] data, PublicKey publicKey) throws Exception {


        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM, KEY_PROVIDER);

        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        int dataSize = cipher.getOutputSize(data.length);

        int blockSize = cipher.getBlockSize();

        int blockNum = 0;

        if (data.length % blockSize == 0) {
            blockNum = data.length / blockSize;
        } else {
            blockNum = data.length / blockSize + 1;
        }
        byte[] raw = new byte[dataSize * blockNum];
        int i = 0;
        while (data.length - i * blockSize > 0) {
            if (data.length - i * blockSize > blockSize) {
                cipher.doFinal(data, i * blockSize, blockSize, raw, i * dataSize);
            } else {
                cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * dataSize);
            }

            i++;

        }
        return raw;
    }



    public static String sign(byte[] encoderData, PrivateKey privateKey) throws Exception {
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM, KEY_PROVIDER);
        sig.initSign(privateKey);
        sig.update(encoderData);
        return new String(Base64.getEncoder().encode(sig.sign()));
    }

    /**
     * 校验数字签名
     */
    public static boolean verify(byte[] encoderData, String sign, PublicKey publicKey) throws Exception {

        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM, KEY_PROVIDER);
        sig.initVerify(publicKey);
        sig.update(encoderData);
        return sig.verify(Base64.getDecoder().decode(sign.getBytes()));
    }


    // 使用N、e值还原公钥
    public static PublicKey getPublicKey(String modulus, String publicExponent) throws NoSuchAlgorithmException, InvalidKeySpecException {
        BigInteger bigIntModulus = new BigInteger(modulus);
        BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus,
                bigIntPrivateExponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    // 使用N、d值还原私钥
    public static PrivateKey getPrivateKey(String modulus, String privateExponent) throws NoSuchAlgorithmException, InvalidKeySpecException {
        BigInteger bigIntModulus = new BigInteger(modulus);
        BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
        RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigIntModulus,
        bigIntPrivateExponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
}
